import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';
import { Component, OnInit } from '@angular/core';
// import { ToastService, UploadConfig } from 'ng-tui';
import { GlobalService, AuthService } from '../../../../cores/services';
import { ManageService } from '../../services/manage.service';
import { Manage } from '../../interfaces/manage.interface';
import { ActivatedRoute, Router } from '@angular/router';
import { Pagination, ConfirmService, ToastService, ModalService } from 'ng-tui';
import { ApiData, SearchParams } from '../../../../cores/classes';
import { Goods } from './../../interfaces/manage.interface';
import { skipWhile, switchMap } from 'rxjs/operators';
import { ModalComponent } from './modal.component';

@Component({
    templateUrl: './district-manage.component.html',
    providers: [Location, { provide: LocationStrategy, useClass: PathLocationStrategy }],
})
export class DistrictManageComponent implements OnInit {

    theads = ['#', '国家', '省', '市', '区', '详细地址', '区域名称', '区域编号', '操作'];

    search = new SearchParams({ start: '', end: '' });

    list = new Array<Goods>();

    loading = false;
    goods: Goods = {};
    pagination = new Pagination();

    constructor(
        private activatedRoute: ActivatedRoute,
        private router: Router,
        private confirm: ConfirmService,
        private toast: ToastService,
        public global: GlobalService,
        private manageService: ManageService,
        private modal: ModalService,
    ) { }

    ngOnInit() {
        this.activatedRoute.url
            .pipe(skipWhile(() => this.router.url !== '/manage/District'))
            .subscribe(() => this.loadDatas());
        this.loadDatas();
    }

    doSearch() {
        this.pagination.reset();
        this.loadDatas();
    }

    doReset() {
        this.search.clean();
        this.doSearch();
    }

    loadDatas() {
        this.loading = true;
        this.manageService.searchGoods(this.pagination, this.search)
            .subscribe({
                next: res => {
                    this.pagination.total = res.datas.total;
                    this.list = res.datas.rows;
                },
                complete: () => this.loading = false
            });
    }

    confirmDelete(id: number) {
        this.confirm.danger('删除确认', `您确认删除该区域吗？`)
            .pipe(switchMap<void, ApiData>(() => this.manageService.deleteGoods(id)))
            .subscribe(() => {
                this.list.splice(this.list.indexOf(this.goods), 1);
                this.toast.success('删除成功', `成功删除区域'`);
                this.loadDatas();
            });
    }
    showEditModal(item: Goods) {
        const modal = this.modal.create(ModalComponent, { center: true });
        modal.instance.goods = Object.assign(modal.instance.goods, item);
        modal.open().subscribe(() => {
            this.toast.success('保存成功', '成功保存区域');
            this.loadDatas();
        });
    }

}
